import React, { useState, useEffect } from 'react';
import { Modal, Button, Card, Typography, Tag, Progress, Alert, Row, Col, Spin } from 'antd';
import { DownloadOutlined, FileTextOutlined, CheckCircleOutlined, RocketOutlined, FileExcelOutlined, FileWordOutlined } from '@ant-design/icons';
import { ExportFormat } from '../../types';
import { projectApi } from '../../services/api';

const { Title, Text, Paragraph } = Typography;

interface ExportModalV2Props {
  visible: boolean;
  onCancel: () => void;
  projectName: string;
  projectNameEn: string;
}

const ExportModalV2: React.FC<ExportModalV2Props> = ({
  visible,
  onCancel,
  projectName,
  projectNameEn
}) => {
  const [exportFormats, setExportFormats] = useState<ExportFormat[]>([]);
  const [loadingFormats, setLoadingFormats] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [exportProgress, setExportProgress] = useState(0);
  const [selectedFormat, setSelectedFormat] = useState<ExportFormat | null>(null);
  const [exportSuccess, setExportSuccess] = useState(false);

  // 从后端获取导出格式列表
  useEffect(() => {
    if (visible) {
      setLoadingFormats(true);
      projectApi.getExportFormats()
        .then(res => {
          setExportFormats(res.formats || []);
        })
        .catch(err => {
          console.error('Failed to load export formats:', err);
          // 如果加载失败，使用默认格式
          setExportFormats([{
            format: 'json',
            name: 'JSON文件',
            extension: '.json',
            description: '轻量级的JSON格式文件，适合程序处理和API调用'
          }]);
        })
        .finally(() => {
          setLoadingFormats(false);
        });
    }
  }, [visible]);

  const getFormatIcon = (format: string) => {
    switch (format) {
      case 'excel':
        return <FileExcelOutlined style={{ color: '#52c41a', fontSize: '32px' }} />;
      case 'json':
        return <FileTextOutlined style={{ color: '#1890ff', fontSize: '32px' }} />;
      case 'markdown':
        return <FileTextOutlined style={{ color: '#fa8c16', fontSize: '32px' }} />;
      case 'word':
        return <FileWordOutlined style={{ color: '#2b579a', fontSize: '32px' }} />;
      default:
        return <FileTextOutlined style={{ color: '#8c8c8c', fontSize: '32px' }} />;
    }
  };

  const handleExport = async (format: ExportFormat) => {
    try {
      setSelectedFormat(format);
      setExporting(true);
      setExportProgress(0);
      setExportSuccess(false);
      
      // 模拟导出进度
      const progressInterval = setInterval(() => {
        setExportProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + Math.random() * 15;
        });
      }, 300);

      // 调用导出接口
      const blob = await projectApi.exportProject(projectNameEn, format.format);
      
      clearInterval(progressInterval);
      setExportProgress(100);
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      const ts = new Date().toISOString().replace(/[:.]/g, '-');
      a.href = url;
      a.download = `${projectNameEn}_parameters_${ts}${format.extension || ''}`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
      
      setExportSuccess(true);
      
      setTimeout(() => {
        setExporting(false);
        setExportProgress(0);
        setExportSuccess(false);
        setSelectedFormat(null);
        onCancel();
      }, 2000);
      
    } catch (error) {
      console.error('Export failed:', error);
      setExporting(false);
      setExportProgress(0);
    }
  };

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <RocketOutlined style={{ color: '#722ed1' }} />
          <span>导出项目参数</span>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      width={700}
      footer={[
        <Button key="cancel" onClick={onCancel} disabled={exporting}>
          {exportSuccess ? '完成' : '取消'}
        </Button>
      ]}
      destroyOnClose
    >
      <div style={{ padding: '8px 0' }}>
        {/* 项目信息 */}
        <Card size="small" style={{ marginBottom: '24px', background: '#f8f9fa' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <div style={{ 
              width: '48px', 
              height: '48px', 
              borderRadius: '8px',
              background: 'linear-gradient(135deg, #722ed1 0%, #9254de 100%)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: 'white',
              fontSize: '20px',
              fontWeight: 'bold'
            }}>
              {projectName.charAt(0)}
            </div>
            <div>
              <Title level={4} style={{ margin: 0, color: '#262626' }}>{projectName}</Title>
              <Text type="secondary" style={{ fontSize: '12px' }}>{projectNameEn}</Text>
            </div>
          </div>
        </Card>

        <Alert
          message="导出说明"
          description="选择所需的格式并点击导出，将生成对应的项目参数文件。"
          type="info"
          showIcon
          style={{ marginBottom: '24px' }}
        />

        {/* 导出格式选择 */}
        <Title level={5} style={{ margin: '0 0 16px 0', color: '#262626' }}>
          选择导出格式
        </Title>
        
        {loadingFormats ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: '16px', color: '#8c8c8c' }}>正在加载可用格式...</div>
          </div>
        ) : exportFormats.length === 0 ? (
          <Alert
            message="暂无可用格式"
            description="当前没有可用的导出格式，请稍后再试。"
            type="warning"
            showIcon
          />
        ) : (
          <Row gutter={[16, 16]}>
            {exportFormats.map(format => (
            <Col span={12} key={format.format}>
              <Card
                hoverable
                style={{
                  border: selectedFormat?.format === format.format ? '2px solid #722ed1' : '1px solid #e8e8e8',
                  background: selectedFormat?.format === format.format ? '#f9f0ff' : 'white',
                  transition: 'all 0.3s ease',
                  cursor: exporting ? 'not-allowed' : 'pointer',
                  opacity: exporting && selectedFormat?.format !== format.format ? 0.5 : 1
                }}
                onClick={() => !exporting && setSelectedFormat(format)}
              >
                <div style={{ textAlign: 'center', padding: '16px 8px' }}>
                  <div style={{ marginBottom: '12px' }}>
                    {getFormatIcon(format.format)}
                  </div>
                  <Title level={5} style={{ margin: '0 0 8px 0', color: '#262626' }}>
                    {format.name}
                  </Title>
                  <Tag color="purple" style={{ marginBottom: '8px' }}>
                    {format.extension}
                  </Tag>
                  <Paragraph 
                    style={{ 
                      fontSize: '12px', 
                      color: '#8c8c8c', 
                      margin: '0 0 16px 0',
                      lineHeight: '1.4'
                    }}
                  >
                    {format.description}
                  </Paragraph>
                  <Button
                    type="primary"
                    icon={<DownloadOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleExport(format);
                    }}
                    loading={exporting && selectedFormat?.format === format.format}
                    disabled={exporting}
                    style={{ width: '100%', background: '#722ed1', borderColor: '#722ed1' }}
                  >
                    {exporting && selectedFormat?.format === format.format ? '导出中...' : '导出'}
                  </Button>
                </div>
              </Card>
            </Col>
            ))}
          </Row>
        )}

        {/* 导出进度 */}
        {exporting && selectedFormat && (
          <div style={{ marginTop: '24px' }}>
            <Alert
              message={`正在导出 ${selectedFormat.name}...`}
              type="info"
              showIcon
              style={{ marginBottom: '12px' }}
            />
            <Progress
              percent={Math.round(exportProgress)}
              status={exportProgress === 100 ? 'success' : 'active'}
              strokeColor={{
                '0%': '#722ed1',
                '100%': '#9254de',
              }}
            />
          </div>
        )}

        {/* 导出成功 */}
        {exportSuccess && (
          <div style={{ marginTop: '24px' }}>
            <Alert
              message="导出成功！"
              description="文件已开始下载，请检查您的下载文件夹。"
              type="success"
              showIcon
              icon={<CheckCircleOutlined />}
            />
          </div>
        )}

        {/* 导出说明 */}
        <Alert
          message="导出说明"
          description={
            <div>
              <p>• 导出的文件将包含项目的完整参数信息</p>
              <p>• 文件名会自动添加时间戳和标识以避免重复</p>
              <p>• 如果下载没有开始，请检查浏览器的下载设置</p>
              <p>• 导出的文件可在其他环境中导入或用于数据备份</p>
            </div>
          }
          type="info"
          showIcon
          style={{ marginTop: '16px' }}
        />
      </div>
    </Modal>
  );
};

export default ExportModalV2;

